/**
 * 封装网络请求
 * */

import axios from 'axios';
import qs from 'querystring';
import store from '../store'


const errroHandle = (status,other)=>{
  switch (status) {
    case 400:
      console.log('服务器无法理解请求信息');
      break;
    case 401:
      console.log('用户信息验证失败');
      break;
    case 403:
      console.log('请求被限制');
      break;
    case 404:
      console.log('客户端请求信息错误');
      break;
    default:
      console.log(other);
      break;
  }
};

const instance = axios.create({
  timeout:5000
});

instance.defaults.baseUrl = '';
// instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


instance.interceptors.request.use(config=>{
  if (config.method === 'post'){
   config.data =  qs.stringify(config.data);

  }
  if (store.state.tokin){
    config.headers.Authorization = store.state.tokin
  }
  return config;
},error => Promise.reject(error));


instance.interceptors.response.use(
  response =>response.status === 200?Promise.resolve(response):Promise.reject(response),
  error => {
    const {response} = error;
    if (response){
      errroHandle(response.status,response.data);
      return Promise.reject(response);
    }else {
      console.log('请求被中断');
    }
  }
);

export default instance;
